{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qFdPvlXBOdUN"
      },
      "source": [
        "# Gemini API: Text Classification\n",
        "\n",
        "---\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/json_capabilities/Text_Classification.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xHxb-dlhMIzW"
      },
      "source": [
        "You will use the Gemini API to classify what topics are relevant in the text."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SmNOGuCRK0xk"
      },
      "source": [
        "## Install dependencies"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AQJjzmYgH3sX"
      },
      "outputs": [],
      "source": [
        "%pip install -U -q \"google-genai>=1.0.0\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MUXex9ctTuDB"
      },
      "source": [
        "## Set up your API key\n",
        "\n",
        "To run the following cell, your API key must be stored it in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see the [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) quickstart for an example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wltbMJLIIXGk"
      },
      "outputs": [],
      "source": [
        "from google.colab import userdata\n",
        "from google import genai\n",
        "\n",
        "GOOGLE_API_KEY = userdata.get(\"GOOGLE_API_KEY\")\n",
        "client = genai.Client(api_key=GOOGLE_API_KEY)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Gv7pRql-LGGr"
      },
      "source": [
        "## Example"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ba3pV3hwLKET"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "## The Enduring Appeal of Sports: More Than Just Games\n",
              "\n",
              "Sports, in their myriad forms, represent a fundamental aspect of the human experience. From the individual pursuit of a personal best to the collective fervor of a national championship, they offer a unique blend of physical exertion, strategic thinking, and emotional engagement. The appeal transcends mere entertainment; sports are a microcosm of life itself, teaching invaluable lessons about teamwork, discipline, perseverance, and the ability to cope with both victory and defeat. They connect us, forging bonds across geographical boundaries and cultural divides, uniting individuals under the banner of shared passion and admiration. This shared experience creates a sense of community and belonging, particularly in an increasingly fragmented world.\n",
              "\n",
              "The benefits of sports extend far beyond the playing field. Regular participation fosters physical and mental well-being, reducing the risk of chronic diseases and improving cognitive function. Active involvement, whether as a player, coach, or even a dedicated fan, provides a healthy outlet for stress and promotes a positive self-image. Furthermore, sports often act as a catalyst for economic growth, generating revenue through ticket sales, merchandise, advertising, and tourism. Entire industries thrive around the sporting world, providing employment opportunities and contributing significantly to local and national economies.\n",
              "\n",
              "Beyond the tangible benefits, sports also serve as a powerful platform for social change. Athletes have increasingly used their platform to advocate for issues they believe in, raising awareness about important causes like racial injustice, gender equality, and climate change. Think of Colin Kaepernick's kneeling protest or Megan Rapinoe's advocacy for equal pay; these moments demonstrate the potential of sports figures to spark meaningful conversations and challenge societal norms. By leveraging their influence, athletes can inspire action and contribute to a more just and equitable world.\n",
              "\n",
              "Interestingly, this social activism mirrors trends in the world of **art**. Just as athletes are increasingly using their platforms to speak out on social issues, artists are using their work to address societal challenges, provoke thought, and inspire change. From protest songs to politically charged paintings, art and sport both serve as powerful mediums for reflecting and shaping the world around us. They both provide a space for expression, fostering dialogue and encouraging individuals to engage with complex issues in a meaningful way.\n",
              "\n",
              "In conclusion, the enduring appeal of sports lies in its multifaceted nature. It’s a source of entertainment, a pathway to physical and mental well-being, an engine for economic growth, and a platform for social change. Like art, it reflects the human condition, allowing us to express our emotions, celebrate our triumphs, and confront our challenges. Whether we are athletes, fans, or simply observers, sports hold a significant place in our lives, reminding us of the power of human potential and the importance of collective effort. They are more than just games; they are a reflection of who we are, and who we aspire to be.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from IPython.display import Markdown\n",
        "\n",
        "MODEL_ID = \"gemini-2.5-flash\" # @param [\"gemini-2.5-flash-lite\",\"gemini-2.5-flash\",\"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\":true, isTemplate: true}\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"Generate a 5 paragraph article about Sports, include one other topic\",\n",
        ")\n",
        "article = response.text\n",
        "Markdown(article)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s6OUVYx5LfJz"
      },
      "outputs": [],
      "source": [
        "import enum\n",
        "from typing_extensions import TypedDict  # in python 3.12 replace typing_extensions with typing\n",
        "\n",
        "from google.genai import types\n",
        "\n",
        "\n",
        "class Relevance(enum.Enum):\n",
        "  WEAK = \"weak\"\n",
        "  STRONG = \"strong\"\n",
        "\n",
        "class Topic(TypedDict):\n",
        "  topic: str\n",
        "  relevance: Relevance\n",
        "\n",
        "\n",
        "sys_int = \"\"\"\n",
        "Generate topics from text. Ensure that topics are general e.g. \"Health\".\n",
        "Strong relevance is obtained when the topic is a core tenent of the content\n",
        "and weak relevance reflects one or two mentions.\n",
        "\"\"\"\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=article,\n",
        "    config=types.GenerateContentConfig(\n",
        "        system_instruction=sys_int,\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=list[Topic],\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "owfUpKKHL0tF"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[{'relevance': <Relevance.STRONG: 'strong'>, 'topic': 'Sports'},\n",
            " {'relevance': <Relevance.STRONG: 'strong'>, 'topic': 'Health'},\n",
            " {'relevance': <Relevance.WEAK: 'weak'>, 'topic': 'Economics'},\n",
            " {'relevance': <Relevance.STRONG: 'strong'>, 'topic': 'Social Issues'},\n",
            " {'relevance': <Relevance.WEAK: 'weak'>, 'topic': 'Art'}]\n"
          ]
        }
      ],
      "source": [
        "from pprint import pprint\n",
        "\n",
        "pprint(response.parsed)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1ZmEIByML5ZG"
      },
      "source": [
        "## Summary\n",
        "Now, you know how to classify text into different categories. Feel free to experiment with other texts, or provide a specific set of possible topics.\n",
        "\n",
        "Please see the other notebooks in this directory to learn more about how you can use the Gemini API for other JSON related tasks."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "Tce3stUlHN0L"
      ],
      "name": "Text_Classification.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
